<?php
    
	if (!isset($_GET["userid"]) || !isset($_GET["entity"]) || !isset($_GET["rank"]) || !isset($_GET["type"])) {
        die("Give me params!!!");
    }
    
    $exists = false;
    
    include_once "include/constants.php";
	
    define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

    try {
        $conn = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME, DB_USER, DB_PASS);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
         
        $stmt = $conn->prepare('select count(*) as cnt from thumbs where userid = :userid and entity = :entity and type = :type');
		$stmt->execute(array("userid" => $_GET["userid"], "entity" => $_GET["entity"], "type" => $_GET["type"]));
        
        $thumbs_data = $stmt->fetch();
        if ($thumbs_data['cnt'] > 0) {
            $exists = true;
        }
        
        if ($exists) {
            $stmt = $conn->prepare('update thumbs set rank = :rank where userid = :userid and type = :type and entity = :entity');
            $stmt->execute(array("userid" => $_GET["userid"], "entity" => $_GET["entity"], "type" => $_GET["type"], "rank" => $_GET["rank"]));
        }
        else {
            $stmt = $conn->prepare('insert into thumbs (userid, type, entity, rank)
                                    values (:userid, :type, :entity, :rank)');
            $stmt->bindParam('userid', $_GET["userid"]);
            $stmt->bindParam('entity', $_GET["entity"]);
            $stmt->bindParam('type', $_GET["type"]);
            $stmt->bindParam('rank', $_GET["rank"]);
            $stmt->execute();
        }
        
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    
    echo "Done";
    
?>
